import os
import tempfile
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.colors import black, blue, darkgreen


class DrillScriptPDFGenerator:
    def __init__(self):
        self.styles = getSampleStyleSheet()
        self._setup_chinese_font()
    
    def _setup_chinese_font(self):
        """设置中文字体支持"""
        try:
            # 尝试注册系统中文字体
            font_paths = [
                "C:/Windows/Fonts/simsun.ttc",  # Windows 宋体
                "C:/Windows/Fonts/simhei.ttf",  # Windows 黑体
                "/System/Library/Fonts/PingFang.ttc",  # macOS
                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",  # Linux
            ]
            
            for font_path in font_paths:
                if os.path.exists(font_path):
                    pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                    break
            else:
                # 如果没有找到中文字体，使用默认字体
                print("警告：未找到中文字体，将使用默认字体")
                return
                
        except Exception as e:
            print(f"字体设置失败: {e}")
            return
    
    def _create_title_style(self):
        """创建标题样式"""
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=self.styles['Heading1'],
            fontSize=18,
            spaceAfter=20,
            alignment=1,  # 居中
            textColor=blue,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            title_style.fontName = 'ChineseFont'
            
        return title_style
    
    def _create_heading_style(self):
        """创建小标题样式"""
        heading_style = ParagraphStyle(
            'CustomHeading',
            parent=self.styles['Heading2'],
            fontSize=14,
            spaceAfter=12,
            spaceBefore=20,
            textColor=darkgreen,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            heading_style.fontName = 'ChineseFont'
            
        return heading_style
    
    def _create_subheading_style(self):
        """创建子标题样式"""
        subheading_style = ParagraphStyle(
            'CustomSubHeading',
            parent=self.styles['Heading3'],
            fontSize=12,
            spaceAfter=8,
            spaceBefore=12,
            textColor=black,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            subheading_style.fontName = 'ChineseFont'
            
        return subheading_style
    
    def _create_content_style(self):
        """创建内容样式"""
        content_style = ParagraphStyle(
            'CustomContent',
            parent=self.styles['Normal'],
            fontSize=11,
            spaceAfter=6,
            leading=14,
            textColor=black,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            content_style.fontName = 'ChineseFont'
            
        return content_style
    
    def _create_info_style(self):
        """创建信息样式（用于参与者信息等）"""
        info_style = ParagraphStyle(
            'CustomInfo',
            parent=self.styles['Normal'],
            fontSize=10,
            spaceAfter=4,
            leading=12,
            textColor=black,
            leftIndent=20,
        )
        
        # 如果设置了中文字体，使用中文字体
        registered_fonts = pdfmetrics.getRegisteredFontNames()
        if 'ChineseFont' in registered_fonts:
            info_style.fontName = 'ChineseFont'
            
        return info_style
    
    def generate_pdf(self, equipment: str, scene_desc: str, plan: dict, script_node: list, output_path: str = None):
        """
        生成演练脚本PDF文件
        
        Args:
            equipment: 设备名称
            scene_desc: 场景描述
            plan: 应急预案字典
            script_node: 脚本节点列表
            output_path: 输出文件路径，如果为None则使用临时文件
            
        Returns:
            生成的PDF文件路径
        """
        if output_path is None:
            # 创建临时文件
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
            output_path = temp_file.name
            temp_file.close()
        
        # 创建PDF文档
        doc = SimpleDocTemplate(output_path, pagesize=A4)
        story = []
        
        # 获取样式
        title_style = self._create_title_style()
        heading_style = self._create_heading_style()
        subheading_style = self._create_subheading_style()
        content_style = self._create_content_style()
        info_style = self._create_info_style()
        
        # 添加主标题
        main_title = f"{equipment} - {scene_desc} 演练脚本"
        story.append(Paragraph(main_title, title_style))
        story.append(Spacer(1, 20))
        
        # 添加应急预案信息
        story.append(Paragraph("应急预案信息", heading_style))
        for field_name, field_content in plan.items():
            # 添加字段标题
            story.append(Paragraph(field_name, subheading_style))
            
            # 添加字段内容
            # 处理换行符
            if isinstance(field_content, str):
                content_lines = field_content.split('\n')
                for line in content_lines:
                    if line.strip():  # 跳过空行
                        story.append(Paragraph(line.strip(), content_style))
            elif isinstance(field_content, list):
                # 如果是列表，转换为字符串
                content_str = str(field_content)
                story.append(Paragraph(content_str, content_style))
            else:
                # 其他类型直接转换为字符串
                content_str = str(field_content)
                story.append(Paragraph(content_str, content_style))
            
            story.append(Spacer(1, 8))
        
        story.append(Spacer(1, 15))
        
        # 添加演练脚本
        story.append(Paragraph("演练脚本", heading_style))
        
        for node in script_node:
            # 添加节点标题
            node_name = node.get('nodeName', '未命名节点')
            node_type = node.get('nodeType', '未知')
            node_order = node.get('nodeOrder', 0)
            
            node_title = f"{node_order}. {node_name} ({node_type})"
            story.append(Paragraph(node_title, subheading_style))
            
            # 处理子节点
            children = node.get('children', [])
            for i, child in enumerate(children, 1):
                child_name = child.get('nodeName', '未命名')
                child_type = child.get('nodeType', '未知')
                child_id = child.get('id', '未知')
                
                # 添加子节点标题
                child_title = f"子节点 {i}: {child_name} ({child_type})"
                story.append(Paragraph(child_title, content_style))
                
                # 添加节点内容
                node_content = child.get('nodeContent', '')
                if node_content:
                    story.append(Paragraph("节点内容:", info_style))
                    # 处理换行符
                    content_lines = node_content.split('\n')
                    for line in content_lines:
                        if line.strip():  # 跳过空行
                            story.append(Paragraph(line.strip(), info_style))
                
                # 添加参与者信息
                participants = child.get('participants', {})
                if participants:
                    story.append(Paragraph("参与者信息:", info_style))
                    story.append(Paragraph(f"姓名: {participants.get('name', '未知')}", info_style))
                    story.append(Paragraph(f"组名: {participants.get('groupName', '未知')}", info_style))
                    story.append(Paragraph(f"组ID: {participants.get('groupId', '未知')}", info_style))
                
                story.append(Spacer(1, 8))
            
            story.append(Spacer(1, 10))
        
        # 生成PDF
        doc.build(story)
        
        return output_path
    
    def generate_pdf_bytes(self, equipment: str, scene_desc: str, plan: dict, script_node: list):
        """
        生成演练脚本PDF文件的字节数据
        
        Args:
            equipment: 设备名称
            scene_desc: 场景描述
            plan: 应急预案字典
            script_node: 脚本节点列表
            
        Returns:
            PDF文件的字节数据
        """
        # 生成临时PDF文件
        temp_path = self.generate_pdf(equipment, scene_desc, plan, script_node)
        
        # 读取文件内容
        with open(temp_path, 'rb') as f:
            pdf_bytes = f.read()
        
        # 删除临时文件
        try:
            os.unlink(temp_path)
        except:
            pass
        
        return pdf_bytes 